Skip to content

Fix to claude - #2429

Closed
filve wants to merge 110 commits into
leejet:masterfrom
filve:fix_to_claude
Closed

filve wants to merge 110 commits into
leejet:masterfrom
filve:fix_to_claude

Conversation

@filve

@filve filve commented Nov 25, 2026 •

Copy link
Copy Markdown

Summary

Related Issue / Discussion

Additional Information

Checklist

filve and others added 30 commits October 7, 2026 19:23
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
The merge from upstream bumped ggml to 66c1a28 for ggml_rope_apply, but
a later commit accidentally reverted the submodule pointer to 89c4413f,
which lacks that op and breaks the build.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
A loader worker that failed to open the model file gave up with a bare
"failed to open" and no hint of the cause, and later requests kept
failing the same way. Retry the open up to five times with backoff
(not for a missing file) and log errno/doserrno on every failed attempt.

Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
Brings in the nine upstream commits since 228c707, including the VAE
decode tile halving on OOM retry and the demotion of resident params to
disk residency when memory reclamation fails.

The only conflict was in ModelManager::ensure_compute_backend_capacity:
both sides added a block before the final capacity report. Keep both,
and apply the memory guard's "never fail a graph that still fits"
fallback before and after the demotion step.

Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
The release job creates a release with the default GITHUB_TOKEN but declared
no permissions, so on repositories whose default token is read-only the
"Create release" step fails with "Resource not accessible by integration".

Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
The guard returned an empty sample for CPU backends, so a CPU-only run
could fill system RAM without the guard ever reacting. On the CPU, measure
system RAM instead: total minus the memory available without swapping,
plus the allocation the graph is about to make, against total physical
memory.

Under pressure the guard releases unpinned weights that can be re-read
from the model file (--params-backend disk). It never fails a graph on the
CPU, since system RAM has no managed capacity, and CPU pressure does not
suspend prefetch for GPU backends.

Expose available_ram_bytes() from backend_fit for the probe, and update
the CLI help, the public header comment and the docs.

Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
…lkan, Linux Vulkan)

The portable workflow only built CPU packages, so a downloaded Windows zip
could never use the GPU ("sd-server detects only the CPU"). Mirror the
configuration already proven by build.yml and add the GPU modules:

- windows-x86_64: CPU + Vulkan (NVIDIA, AMD, Intel)
- windows-x86_64-cuda12: CPU + CUDA 12 with cudart/cublas/cublasLt bundled,
  so only the NVIDIA driver is needed on the target machine
- linux-x86_64: CPU + Vulkan, with an $ORIGIN rpath so the unpacked zip finds
  its shared libraries
- darwin-arm64 unchanged (Metal)

Windows now builds with cl.exe, /bigobj and the shared stable-diffusion
library like build.yml; the server frontend is built as in the main CI.

A manual run can select the packages and the CUDA architectures (a single
architecture shortens the CUDA build a lot). A smoke test runs
"sd-cli --list-devices" on every package, and the release is attached by one
job after all packages succeeded instead of by racing matrix jobs.

package_portable.sh takes PORTABLE_VARIANT (zip name and LEGGIMI wording) and
PORTABLE_REQUIRE_BACKENDS, and refuses to create a GPU package whose backend
module (or, on Windows, CUDA runtime DLLs) is missing.

Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
With dynamic backends ggml loads the GPU modules silently in Release
builds, and on Windows its dl_error() returns an empty string, so a GPU
module that is on disk but fails to load (missing driver, missing
cudart/cublas DLL, wrong version) just made the GPU disappear: "only the
CPU is detected" with no hint why.

After the one-time module load, look for each known GPU module next to the
executable and in the working directory (the places ggml searches). For
every module that is present but provides no device, load it the way ggml
does and log the real reason with a hint: the dlopen error on Linux and
macOS; on Windows the error code and message plus the DLLs the module
imports that the loader cannot find, read from the import table of the
file (new bounds-checked PE reader, tested with truncated and corrupted
images). When no GPU module exists at all, say where it looked.

sd_get_device_count() and sd_list_devices() now share the one-time loader
instead of calling ggml_backend_load_all() themselves.

Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
The loader opened the model file again for every batch of tensors, in every
worker thread: once per component at startup (text encoder, UNet, VAE) and
then again each time weights are loaded back from disk (per segment, per
residency swap, per request). Each open is a chance to fail, and on Windows
it can fail exactly when the system is short of memory or handles
("failed to open '...safetensors'" at VAE decode, after RAM hit 100%).

A new FileHandlePool keeps the read streams open and hands them out to the
workers one at a time. ModelLoader owns one; copies and the per-file readers
used for LoRA tensors share it. A stream is dropped when the file's size or
modification time changes, when it is in an error state, or when its source
is removed. If a read fails the worker reopens the file once and repeats the
read, so a stream that went bad while idle (removable or network storage)
no longer fails the whole generation. The open retry with errno/doserrno
logging moves into the pool and now also covers .ckpt (zip) files.

Measured with a synthetic SD 1.5 checkpoint on CPU: the file is opened 5
times for three server requests instead of 9 per request; an injected EIO is
absorbed and the image is pixel-identical; persistent read errors end in a
clean error. test/file_handle_pool_test.cpp covers reuse, changed and
replaced files, failed streams, limits and concurrent use, and passes under
ASan/UBSan and ThreadSanitizer.

Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
Without a GPU, auto-fit now compares the available RAM with the size of
each component and leaves the ones that do not fit on disk. When it does,
it turns the memory guard on at 90% unless --memory-guard is set.

On CPU backends the memory guard now counts the weights a graph still has
to read from disk before they are loaded. When that total would pass the
threshold and some weights can be released, the graph runs in segments, as
it already does on a GPU, so the peak stays well below the size of the
model. Splitting is skipped when the guard is off or when every weight is
resident, because it could not lower the peak.

Checked with a synthetic SD 1.5 model (128x128, 3 steps, 2 threads, Linux):
with 3.3 GiB of RAM held by another process and a 60% guard, the UNet runs
in 22 segments with a 732 MiB peak instead of 1722 MiB and the image is
identical pixel for pixel. Resident weights and runs without pressure or
without the guard behave as before. Not tested on Windows or with real
models.

Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
new_sd_ctx(), generate_image() and generate_video() now record the
reason of a failure, and sd_get_last_error() returns it with a code:
out of memory, model file, backend, invalid argument, busy or
cancelled. An application can tell "try again with less memory" from
"the file is damaged" instead of reading the log. The state belongs to
the calling thread; errors logged by the model loader threads reach the
thread that reports the failure. C++ exceptions, std::bad_alloc
included, no longer cross the C API.

A test with a limited address space showed the process ending with
std::terminate when a loader thread could not be created while others
were already running. The loader now uses fewer threads, or the
calling thread when none could be started, and the loader threads
report exceptions as a failed load.

sd_get_system_memory() returns total, available and process RAM. The
free memory of the CPU device in sd_get_device_info() is the available
RAM, because ggml reports the total on Linux and macOS.

Checked with a synthetic 2.1 GB SD 1.5 model under a limited address
space: the standard configuration fails with out_of_memory, the same
context generates once the limit is lifted, and weights on disk let
the same request succeed. The Windows branch of system_memory.cpp was
only syntax-checked; macOS was not built.

Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
--profile max|balanced|lite|auto sets, in one option, what a small
machine needs: balanced turns the memory guard on at 90; lite also
puts the text encoder on the CPU, tiles the VAE, runs CFG unbatched
and lowers the guard to 85. An option given on the command line always
wins over the profile, including --memory-guard 0. A profile does not
touch --params-backend or --backend, so --auto-fit keeps deciding
where the weights live, and it never changes the size or the steps of
an image.

auto compares the size of the model files plus a working-memory
reserve with the free memory of the discrete GPU with the most, or
with the available RAM without one, and logs the figures it used. It
leaves the defaults alone when the sizes or the memory are unknown.

parse_options() now records which options were given, through
option_was_given(). The levels below lite (weights streamed from disk,
everything on the CPU) cannot be chosen from the command line; they
are the steps a server takes when a request runs out of memory.

The thresholds of auto are heuristics and have not been tuned on a real
model or a GPU. Checked with the synthetic SD 1.5 model on the CPU: the
three profiles give the same image, and with 3.3 GiB held by another
process auto picks balanced.

Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
SDGenerationParams::resolved_hires_upscaler was assigned only when hires
was enabled, but to_sd_img_gen_params_t() and to_sd_vid_gen_params_t()
copy it into params.hires.upscaler on every request. With hires off that
copied an indeterminate enum value, which UBSan reports as "load of value
..., which is not a valid value for type 'sd_hires_upscaler_t'". The
library does not look at the field while hires is disabled, so nothing
changes in behavior; the member now starts as SD_HIRES_UPSCALER_NONE.

Found by running sd-server under UBSan.

Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
A request that ran the machine out of memory ended in a 500 and left the
server on the configuration that had just failed, so every later request
of that size failed the same way. The context now belongs to a
ContextKeeper (examples/server/recovery.*) and every generation of the
OpenAI, sdapi and sdcpp endpoints goes through ContextKeeper::run().

On out_of_memory or backend (the codes of sd_get_last_error()) it frees
the model, loads it again with the next lighter profile of
max > balanced > lite > lite-disk > lite-cpu and runs the same request
again. Steps that would load the same configuration are skipped, a
device failure jumps to lite-cpu, and from lite on the VAE is decoded in
tiles whatever the request asked. --profile sets the top of the ladder.

After --degradation-cooldown seconds (300; 0 = never) the server climbs
back one profile at the start of the next request. A climb that fails
on its first use is undone and doubles the wait, up to an hour. If the
model cannot be loaded again, requests get 503 "unavailable" and the
load is retried no more than every 15 seconds. --disable-degradation
keeps the old behavior of answering with the error.

Failures are answered with 503 and Retry-After (out of memory, no
context), 400 (invalid_argument) or 500, with a body of
{"error", "code", "retry_after_seconds"}. Async jobs report the same
code in error.code, 429 carries Retry-After, and std::bad_alloc in a
handler becomes a 503. New endpoints: GET /sdcpp/v1/health (status,
profile, counters, last error, queue; it never waits for a running
generation) and GET /sdcpp/v1/resources (system memory and devices).

sd-server now exits with code 1 and a message when it cannot listen or
create its HTTP threads; the second used to end in std::terminate and
the first in a silent exit 0. The lite-disk profile clears --eager-load,
which read every weight into memory and so saved nothing.

test/server_recovery_test.cpp checks the ladder, the step downs, the
climb back, the reload after a failure, the HTTP answers and use from
several threads with a scripted library and clock (114 checks, also
under ASan/UBSan and TSan). Checked with a synthetic SD 1.5 model on
the CPU under address-space limits: a 384x384 request at 2400 MiB steps
down to lite-disk and succeeds, below 2200 MiB it answers 503 and the
server stays up, the climb back and a failed climb behave as described,
and nine parallel requests of the three kinds are all served. The server
and the whole engine built with ASan/UBSan went through the ladder, the
CPU memory-guard scenarios and injected read errors without a report.
Not checked: Windows, GPUs, real models.

Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
recovery.cpp included recovery.h first, which reaches <windows.h> through
common/log.h. windows.h pulls in winsock.h, and the winsock2.h included by
httplib.h then redefines its declarations, so both Windows builds stopped
with hundreds of errors in the Windows SDK headers. Include httplib.h first,
as the other server sources do, and include <exception> in recovery.h for the
type it uses.

Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
package_portable.sh builds the zip from a temporary directory, so a relative
output directory such as the "dist" that the release-portable workflow passes
pointed to a place that does not exist and zip failed. Make the build and
output directories absolute before changing directory.

Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
filve and others added 28 commits October 18, 2026 20:13
…-pull

Brings in the 73 upstream commits since b13a482 (2026-10-20 to 2026-11-05):
cancellation of running server jobs (leejet#2190), recipe based model management
and idempotent model loading (leejet#2176, leejet#2188, leejet#2217, leejet#2221), ADetailer in the
server (leejet#2164), generation metadata returned with the core results (leejet#2206,
which changes generate_image and generate_video), integrated GPUs in the
automatic memory planning (leejet#2228), discrete GPUs preferred in auto-fit
(leejet#2259), Vulkan capacity checks retried after reclaiming memory (leejet#2256),
the layer split fix across CUDA devices (leejet#2262), RPC devices in
--list-devices (leejet#2182), new models and many speed-ups (FLUX.3, Fibo 2.0,
MiniMax-H3, P-H3-Image, MOSS, Z-Image control-net, INT8 CUDA fusions),
Node 24 and ccache in the workflows, a CUTLASS submodule for the CUDA build,
and the ggml sync to 135ce1e.

Conflicts resolved by hand in 25 files, keeping both sides:

- include/stable-diffusion.h, src/stable-diffusion.cpp,
  src/core/ggml_runner.cpp, src/pipeline/diffusion_engine.cpp,
  src/pipeline/image.cpp: upstream's result API stays (generate_image and
  generate_video fill a result out-parameter, free_sd_image_generation_result
  releases it); the fork's classified errors, exception barrier and busy
  check wrap it, so a failed call still records its reason and clears the
  result. memory_guard, disable_backend_fallback and multi_gpu follow
  upstream's last sd_ctx_params_t field. A stop on request is logged as
  information, not as an error.
- src/core/backend_fit.cpp: integrated GPUs are enumerated as upstream now
  does; which device becomes the main one is still decided by the fork's
  rules (discrete before integrated, a card seen by both CUDA and Vulkan
  counts once), which cover the case of leejet#2259 as well.
- src/core/ggml_extend_backend.cpp, CMakeLists.txt: the NVIDIA driver is
  still loaded at run time (sd::cuda_driver; the toolkit provides headers
  only), so upstream's cuda_compiled_arch asks the compute capability
  through it and not through <cuda.h>; the CUTLASS include of upstream
  stays.
- src/model_manager.cpp: the CPU memory guard and upstream's capacity
  rechecks (leejet#2183, leejet#2256) both apply.
- examples/server (runtime, main, async_jobs, routes_*): the context keeper
  is still the only owner of the context, and ServerRuntime has no context
  or mutex of its own. Upstream's model catalog (--model-dir, the
  /sdcpp/v1/models routes, recipes) asks the keeper to load and unload
  (ContextKeeper::load, unload, has_model), so a model loaded from the
  catalog gets the same recovery ladder as the one given with -m, built from
  the options of the new model. ADetailer runs with the context and the
  options of the profile in use. The server still starts without a model.
- Cancellation: every job has a CancelToken that the keeper registers only
  while the job generates. POST /sdcpp/v1/jobs/{id}/cancel answers at once
  when called without ?wait=, as upstream does (the job can still be
  generating, with cancel_requested true); with ?wait=N it waits for the end
  of the job and answers 200, or 202 if it is still ending, which is what
  the fork's guardian expects. cancel_requested is always in the job JSON.
- examples/common/common.{h,cpp}: upstream's --list-devices with RPC devices
  and --taesd-preview-only next to the fork's --profile, --memory-guard,
  --multi-gpu and --disable-backend-fallback.
- .github/workflows/build.yml: upstream's Node 24, ccache and CUDA header
  triggers next to the fork's CPU Docker variant, lowercase image names,
  combined CUDA and Vulkan Windows zip and Italian release notes.
  examples/cli and examples/server CMakeLists: profile.cpp and recovery.cpp
  are added to upstream's source lists.
- docs/backend.md, docs/build.md, examples/server/api.md: the sections of
  both sides are kept. The paragraph on how a layer split assigns blocks is
  the fork's, which is what layer_split_partition.cpp does (the first device
  takes blocks until its free memory is used up), not upstream's
  "proportional" wording.

The ggml submodule moves from dc99877 to 135ce1e, the frontend submodule to
fa93429 and the new thirdparty/cutlass submodule is added, all at upstream's
pins. A checkout needs git submodule update --init --recursive.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
…nload

The fork's hand-built tests followed the API as it was before the merge with
leejet's stable-diffusion.cpp. They are compiled by hand (no CMake target and
no workflow runs them), so the merge commit itself still builds.

- api_robustness: generate_image takes a result out-parameter now; a failed
  call clears it, and a missing one is an invalid argument.
- profile_test: the build command lists the metadata sources of the common
  code, and to_sd_ctx_params_t() has no argument any more.
- server_recovery_test: the build command is updated and the simulated
  library records the model path of each load. 24 new checks cover
  ContextKeeper::load, unload and has_model, which the model catalog of the
  server uses: the old context is freed before the new one is created, the
  ladder is built again from the options of the new model, a failed load
  leaves the server without a model (requests are refused) and can be
  repeated, unloading twice is harmless, and health and state can be read
  while the model changes.
- server_cancel_e2e: without ?wait= the cancel route answers at once with
  the job still generating, as upstream does, so the test polls the job and
  repeats the stop; a new scenario checks ?wait=30, which answers 200 as soon
  as the job has ended.

On the merged tree: api_robustness 30 checks, profile 60, server_recovery 173
(api_robustness and server_recovery with ASan/UBSan, server_recovery also with
TSan), and server_cancel_e2e 35 against the merged sd-server, all passing.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
- README.md, docs/convivenza_applicazioni.md, docs/integrazione_progetti.md:
  the cancel route answers at once with 200 when called without ?wait=, as
  leejet's server does (the job can still be generating, with
  cancel_requested true), and waits only with ?wait=N, answering 200 when the
  job has ended or 202 when it has not, which is what the guardian example
  expects.
- docs/integrazione_progetti.md: the C example and the lifecycle use the
  result API (sd_image_generation_result_t and
  free_sd_image_generation_result); the paragraph on starting without a
  model describes the 503 answer and the model catalog, and says that a
  model loaded from the catalog gets the same recovery ladder; the counts of
  the recovery and cancel tests are updated.
- examples/server/api.md: the cancel example shows cancel_requested.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
When the server stepped down, the CPU took the work and the GPUs were left
behind: `lite` put the text encoder on the CPU, `lite-disk` switched the
auto-fit off, a backend failure jumped straight to `lite-cpu`, and an engine
that could not start a backend quietly turned the whole model into a CPU run.

- profile: `lite` no longer moves the text encoder to the CPU and sets
  `--multi-gpu on` (unless it was set to off); `lite-disk` keeps the
  auto-fit. The new level `lite-hybrid`, between `lite-disk` and `lite-cpu`,
  is where the text encoder goes to the CPU, and only on a machine that has
  an accelerator. Ladder: max > balanced > lite > lite-disk > lite-hybrid >
  lite-cpu. The names and options of `--profile` are unchanged, an explicit
  option still wins, `max` is identical and `include/` is untouched.
- keeper: a backend failure no longer walks down the profiles. The same
  configuration is loaded once more (once per request), then each device the
  engine lists is tried on its own (graphics cards, the vendor's backend
  before Vulkan/OpenCL, most free memory first; accelerators; integrated GPUs
  last; never RPC), and the CPU comes last. Running out of memory on a device
  steps down the profile on that same device. While a GPU is left to try, the
  keeper sets disable_backend_fallback, so the engine does not fall back to
  the CPU by itself. The climb back tries the preferred device first, and
  from the CPU goes straight to the profile the server had when the device
  failed. A placement written in --backend is not rewritten.
- visibility: /sdcpp/v1/health reports device, cpu_modules and
  fallback_devices, and the counters retries and device_switches; the status
  is degraded on another device too. The start-up log tells the order of the
  spare devices, the device in use and the modules the CPU computes.
- the --profile help text no longer says that lite uses the CPU.

Verification: profile_test 74 checks and server_recovery_test 234 checks
(simulated library, device list and clock), the second also under
ASan/UBSan/TSan; seven mutations of the device-failure code are all caught.
On the CPU-only machine used here, sd-server with the synthetic model still
steps down to lite-disk under a memory limit, and the cancel (35 checks) and
model catalog (15 checks) runs pass. Nothing has run on a real GPU.

Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
- examples/server/api.md: the ladder with lite-hybrid and what each profile
  sets, a "Device failures" section (the order of the devices, the engine's own
  CPU fallback switched off while a GPU is left, the climb back), and the new
  fields and counters of GET /sdcpp/v1/health.
- examples/server/README.md, docs/performance.md: the same in short; `lite`
  does not use the CPU any more, and the CPU shares the work only from
  lite-hybrid on.
- docs/integrazione_progetti.md: the feature table, the recovery section, the
  profiles, and a new item 24 with the problem, the change, the checks that
  were run and what was not tried (a real GPU, several GPUs, Windows).
- docs/convivenza_applicazioni.md: the recovery ladder, `lite` with an explicit
  --backend, the CPU load of the text encoder, and the answers a client gets.

Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
…-pull

Brings in the one upstream commit since 58bb3c1 (2026-11-06): support for
packed ComfyUI INT4 convrot models (leejet#2276).

Checkpoints in the convrot_w4a4 and asym_w4a8_int8 formats load directly,
also when they mix packed INT4, INT8 tensorwise and floating-point layers.
The packed bytes stay as they are in the file (TensorStorage::w4_convrot_kind
and logical_ne0()), they are never converted to GGUF blocks, and LoRA is
still applied at runtime. New kernels for the CPU, CUDA/HIP/MUSA and Vulkan
are registered through the same extension API as INT8. SD_USE_UPSTREAM_GGML
builds refuse these formats. The ggml submodule does not change.

No conflicts. The fork and upstream both changed src/model_loader.cpp and
src/pipeline/diffusion_engine.cpp, in different places: upstream's changes
are applied as they are and the fork's loader and pipeline changes stay.

Checked on CPU-only builds. The library built from this src/ compiles
without new warnings, and the fork's test programs pass against it from
this tree, with the ASan, UBSan and TSan variants where they exist. A real
sd-server built from this src/ with the examples of fix_to_claude passes the
stop-a-job and model catalogue checks on a synthetic model and steps down
under a memory limit as before. Small synthetic safetensors files in both
packed INT4 formats load through the fork's loader with the expected flags,
shapes and bytes, and malformed ones are refused for the right reason.
Not tried: CUDA and Vulkan builds and any real GPU, so the new GPU kernels
are untested in this fork.

Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
First of four steps towards upstream 3b12781: upstream up to leejet#2309
(size layer-split ranges in proportion to device capacity), including
leejet#2294, leejet#2303, the INT4/INT8 kernels and the new model families.

Conflicts resolved:
- examples/server/async_jobs.{h,cpp}: keep the ContextKeeper attempts
  and the CancelToken; each attempt installs upstream's JobCallbacksGuard
  on the context it runs on (stage reporting from leejet#2303), ADetailer marks
  the detailing stage, and the worker records finish_job_progress.
- examples/common/common.h: keep the resolved_hires_upscaler default and
  add upstream's resolved_control_type.
- src/stable-diffusion.cpp: keep run_without_exceptions and add
  sd_set_generation_progress_callback.

Verified with a CPU build (ggml d803c23): the library, sd-cli and
sd-server build; backend_fit_plan_test, model_loader_latency_test,
pe_imports_test, file_handle_pool_test, profile_test,
server_recovery_test and api_robustness pass; sd-server starts without a
model and answers /sdcpp/v1/health, /sdcpp/v1/resources and
/sdcpp/v1/models/status.

Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
Second of four steps towards upstream 3b12781: ggml 1.0.0 (leejet#2354), the
runner and weight-residency refactor (leejet#2321, leejet#2314, leejet#2322), configurable
job queue limits (leejet#2316), interleaved image prompts (leejet#2341), MiniMax-H3
image and the HIP/CUDA kernel work.

Conflicts resolved:
- src/core/ggml_runner.cpp, src/core/execution_engine.cpp: upstream moved
  graph execution into the new execution engine; the out-of-memory and
  backend error codes, and segmenting on the CPU when weights stream from
  disk, now live there.
- src/model_manager.cpp: ensure_compute_backend_capacity delegates to
  ExecutionEngine::ensure_capacity. The memory guard reaches it through
  three DeviceResidencyManager hooks (memory_guard_ok, _observe and
  _unreachable): blocks are freed until the request fits and the usage is
  under the guard threshold, and a request that fits still runs when the
  threshold cannot be reached. test/memory_guard_engine_test.cpp covers
  it and fails when the hooks are removed.
- examples/server: each ContextKeeper attempt installs upstream's
  PromptImageCallbackGuard on its own context; --degradation-cooldown
  sits next to --max-pending-jobs and --completed-ttl-seconds.
- README.md, examples/server/README.md: keep the fork's releases link and
  the "When the memory runs short" section in the new layout.

Verified with a CPU build (ggml eeda9ec4): the library, sd-cli and
sd-server build; backend_fit_plan_test, model_loader_latency_test,
pe_imports_test, file_handle_pool_test, profile_test,
server_recovery_test, api_robustness and memory_guard_engine_test pass;
sd-server starts without a model and answers /sdcpp/v1/health and
/sdcpp/v1/resources.

Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
Third of four steps towards upstream 3b12781: the opaque C API with
options, tensors and results (leejet#2365).

The fork's additions move to the new API:
- multi_gpu, memory_guard and disable_backend_fallback are context
  options (sd::ContextConfig, registered in src/api/options.cpp) that
  sd-cli and sd-server set through SDContextParams::to_context_opt().
- Our classified error code is renamed sd_get_last_error_code(), since
  upstream's sd_get_last_error() now returns the diagnostic text.
  sd_ctx_create, sd_generate_image and sd_generate_video record it again
  (src/api/api.cpp); the device, system-memory and error-code functions
  stay in the public header.
- ContextKeeper creates contexts with sd_ctx_create() from the settings
  of each profile; its create_context hook takes SDContextParams. Every
  attempt builds fresh image or video options and forces VAE tiling with
  the vae_tiling.enabled key; ADetailer follows the keeper's context.
- Settings that became std::optional are read with the library defaults
  (profiles, keeper, conditioning-cache check); the obsolete seed
  workaround in sd-server is gone, since an unset seed is now random.
- test/profile_test, server_recovery_test and api_robustness use the new
  API; the scripted contexts are real sd_ctx_t objects, as sd_ctx_free()
  deletes them.

Verified with a CPU build: the library, sd-cli and sd-server build; all
eight unit-test programs pass, server_recovery_test also eight times in
a row and under ASan and TSan; sd-server answers /sdcpp/v1/health,
/sdcpp/v1/resources and refuses img_gen with model_not_loaded; sd-cli
reports a missing model as model_file. docs/integrazione_progetti.md
still shows the old API in its C examples; the docs follow after the
last step.

Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
Upstream leejet#2309 made the layer split size its ranges in proportion to the
device capacities, while the fork's multi-GPU planner still estimated
the earlier fill-first placement. --layer-split-fill (context option
layer_split_fill) now offers both, and the split and the planner share
one implementation in src/core/layer_split_partition.*:

- proportional: every device takes the same fraction of its capacity,
  so each keeps room for computing (upstream's behaviour);
- fill-first: the first device takes as many layers as it can, the next
  ones the rest (the fork's earlier behaviour);
- auto (default): when auto-fit plans a split it tries both fills and
  keeps the one that leaves more modules resident on the GPUs,
  proportional on a tie, and the split then fills the devices that way;
  a split given with --backend is proportional over discrete GPUs and
  fill-first as soon as an integrated GPU or the CPU takes part.

The log names the fill of each split, docs/guides/backend.md describes
the option, test/layer_split_fill_test.cpp covers the three modes and
test/backend_fit_plan_test.cpp the planner's choice.

Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
…art 1)

The last step towards upstream master comes in three parts. This first
one takes the commits before the Diffusion Graph Language rewrite:

- two unused ggml compat functions removed, so the library links
  against a shared libggml 1.0.0 (leejet#2363);
- asym_w4a8_int8 defaults to group size 16, as in ComfyUI (leejet#2388);
- batched spatial padding in the Hunyuan causal convolutions (leejet#2374)
  and fewer CUDA launches in the H3 VAE encoder (leejet#2369);
- documentation: Windows ROCm 0xC0000135, Off Grid AI, the server's
  browser notification (leejet#2356, leejet#2372, leejet#2318).

The merge is clean; no fork code changes.

Verified with a CPU build: the library, sd-cli and sd-server build, and
all nine unit-test programs pass.

Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
…art 2)

Brings in the Diffusion Graph Language runtime (leejet#2396) and the commits
after it: MOSS-Image edit LoRAs (leejet#2203), runtime LoRA counts (leejet#2400),
immediate LoRA merges for INT8 weights (leejet#2403), one server context with
on-demand model loading (leejet#2404), Qwen Image 2.1 prefix caching (leejet#2405)
and idle TTLs for model weights (leejet#2406). The server changes of leejet#2404
and leejet#2406 come in the same merge so that sd-server is ported once.

src/pipeline and src/stable-diffusion.cpp are gone; the fork's
additions move into the graph runtime:
- CPU fallback: ModelRuntime::configure_backends() falls back to the cpu
  backend, with a warning, when a module's backend cannot be
  initialized; disable_backend_fallback (also a DGL context option)
  makes it fail with SD_ERROR_BACKEND instead.
- memory_guard is a DGL context option for the context's ModelManager.
  ModelManager::ResourceHandle, the residency manager the models use,
  forwards the guard hooks and honours the prefetch suspension.
- layer_split_fill is applied when the context is created; multi_gpu is
  checked there. The multi-GPU planner, which upstream no longer calls,
  picks the device of each module when auto-fit is on, more than one
  GPU is present and no backend was given (planned_backend_spec() in
  src/api/generation_program.cpp); the run plan places the weights.
- The SD2 v-parameterization probe reports a failed compute instead of
  aborting.
- sd_ctx_create, sd_ctx_set_model_options*, sd_generate_image and
  sd_generate_video record the error code again; a load failure with no
  deeper cause is model_file.

sd-server keeps the ContextKeeper as the owner of the context:
- requests pick their model as upstream does (recipe and models in the
  body); the switch goes through ContextKeeper::load(), so the profile
  ladder and the recovery cover it too;
- sd_ctx_mutex serializes model switches, generations and DGL scripts;
  a DGL script runs on the keeper's context, or on a temporary one while
  no model is loaded (ContextKeeper::with_context()); the idle TTL
  release does not wait for a running generation (try_with_context());
- every context the keeper creates gets the server's file-access policy
  (create_context_from_params() + apply_server_file_access());
- /sdcpp/v1/models/load and /unload stay, rebuilt on
  resolve_model_selection(), as do /sdcpp/v1/health and /resources;
- /sdcpp/v1/upscale and the server-side ADetailer go, as upstream did:
  both are DGL scripts now.

Tests: memory_guard_engine_test follows the new capacity hook;
server_recovery_test checks with_context() and try_with_context()
(red with both behaviours broken); api_robustness expects a missing
model file at the first generation, where the weights load now;
server_cancel_e2e.py uses 100 steps, the server's maximum.

docs: the C API section of docs/integrazione_progetti.md uses the
opaque options; backend.md says what the multi-GPU planner decides
with DGL; api.md documents the kept load/unload routes.

Verified with a CPU build: the library, sd-cli and sd-server build; all
nine unit-test programs pass, server_recovery_test eight times in a row
and twice under TSan with no warnings; with a synthetic SD 1.5 model
(random weights) sd-cli generates, falls back to the cpu backend for
--backend vulkan0 and fails as backend with --disable-backend-fallback,
and test/server_cancel_e2e.py passes its 35 checks against a real
sd-server. A scratch smoke test of the server (20 checks: no model, DGL
jobs with and without a model, models/load and unload, a job that picks
its model, the idle release) passes too.

Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
…art 3)

Brings in the last five upstream commits:
- LoRA: a mixed-type add the backend rejects falls back to F32 (leejet#2383);
- the hires refine schedule keeps at least one sigma (leejet#2361);
- A1111 sdapi metadata endpoints and /sdapi/v1/interrupt (leejet#2349);
- converter metadata in GGUF exports (leejet#2409);
- a HiDream-O1 example image without noise dots (leejet#2407).

The merge is clean. /sdapi/v1/interrupt used the server's raw context,
which this fork does not have: the running A1111 generation now carries
a CancelToken that the preview state holds while it runs, and the
interrupt stops it through ContextKeeper::cancel(), so only that
generation stops.

test: the server_recovery_test check "with stops arriving, still never
two generations at the same time" failed now and then. On a busy
machine the stop thread cancelled all 160 jobs before any of them
started, so no generation ran and the count stayed at 0, not 1. The
stops now reach one job in five; a new check counts the jobs that run
to their end, and the test still fails when run() loses its lock. The
concurrent load/unload check waits for its readers before the model
changes, for the same reason.

docs: entry 25 of the fork history in docs/integrazione_progetti.md
describes the whole DGL sync and what was tested.

Verified with a CPU build: the library, sd-cli and sd-server build; all
nine unit-test programs pass; server_recovery_test passes eight times
on a machine kept busy (it failed four times in six before the fix),
six times idle and twice under TSan with no warnings; with the
synthetic SD 1.5 model, test/server_cancel_e2e.py passes its 35 checks
and the scratch smoke test of the server passes its 22 checks,
/sdapi/v1/interrupt included; the C example of the guide builds with
-Wall -Wextra and makes its 512x512 image.

Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
master to fix to claude
Since upstream leejet#2365, merged with the last sync, the server accepts at
most 100 sampling steps, and the test still asked for 500 in three
jobs: run against a real sd-server it stopped at the first one with
"invalid generation parameters". At 100 steps the jobs still run long
enough for every scenario (about 80 s on a CPU with a small model). The
run without a server was not affected.

Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
The engine keeps, for the whole process, a record of how each device,
the RAM and the disk are doing (src/core/device_health.*). A component
under strain offers less of its capacity, one step per level (85%, 70%,
55%); an excluded one offers nothing and is never computed on. A level
rises by one for a compute that fails, a backend that does not start,
the memory guard that cannot reach its threshold or a read of the
weights that fails (events less than 10 s apart count once), and comes
down one step after each quiet period of 300 s. Outside watchers report
signals with a source and a duration; a signal reaches the other
listings of the same card, a failure of one backend does not.

- C API, additions only: sd_device_health_t, sd_get_device_health(),
  sd_report_device_pressure() and sd_resume_device_health().
- The layer split gives each device its share of capacity, the run plan
  and the multi-GPU planner their share of memory, and an excluded
  device is never the default one. When the record changes, the next
  generation releases the cached models and places them again.
- The engine refuses to compute on an excluded device (a backend error
  at the start of the segment), computes on the CPU with 25% fewer
  threads per level and does not fall back to an excluded CPU. The RAM
  is never cut below the share of level 3; with the disk excluded,
  weights that would be read from it during the run are refused as out
  of memory.
- sd-server: the context keeper skips excluded devices and does not
  climb back to them. A guardian (examples/server/guardian.*) stops all
  work when a component is reported critical or every compute device is
  excluded: the generation in progress ends with the code halted, new
  work is refused with 503 halted and Retry-After, queued jobs wait, and
  /sdcpp/v1/health reports the guardian and every component. It resumes
  when the cause ends, or with POST /sdcpp/v1/guardian/resume; while it
  is halted the keeper neither loads the model again nor steps down.
  --guardian on|off, on by default.
- POST /sdcpp/v1/devices/{device}/pressure takes the reports of outside
  watchers, and termico.py osserva --segnala sends the temperature band
  of an NVIDIA GPU as the level of its device.

The values are provisional. This is a layer of the software, not a
safety system, and the docs say so: examples/server/api.md (Device
health and the guardian), the server README, the README of
scripts/diagnostica_termica, docs/agenti_indipendenti.md (section 9)
and the fork history.

test: device_health_test and server_guardian_test are new, and the
recovery, layer split, planner and termico tests cover the new rules.
server_guardian_e2e.py runs the guardian against a real sd-server: 59
checks, three runs in a row, with a synthetic SD 1.5 model. Every
program of test/ passes, the server tests under ThreadSanitizer too,
and broken versions of the registry, guardian, keeper and termico code
make them fail. Not tried: real GPUs, a layer split between two
devices, Windows.

Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
The values of device health decided on 25 November (3 levels of strain,
15% of the capacity and 25% of the CPU threads per level, a quiet period
of 300 s, and 10 s under which two engine events count once) can now be
read and changed. Without the new option nothing changes.

- C API, additions only: sd_device_health_settings_t,
  sd_get_device_health_settings() and sd_set_device_health_settings().
- sd-cli and sd-server: --device-health with any of the keys levels,
  step, cpu-step, quiet and spacing, e.g. --device-health quiet=600. It
  applies as soon as the options are read, in the DGL mode of sd-cli too;
  values against the rules stop the program at start and say the rules,
  and the log names the values used.
- The registry refuses waits longer than a day and steps whose product
  with the levels would not fit in an int. When the values change, every
  component keeps its state: before, fewer levels could turn a level of
  strain into an exclusion, and more levels could bring an excluded
  device back under strain. The same values written again no longer
  change the revision, which makes the next generation place its models
  again.
- termico.py --segnala reads the levels of its device from
  /sdcpp/v1/health and from the answers to its reports, and never sends
  more than the last level of strain: with two levels the critical band
  is level 2, not an exclusion.

Docs: a "Device health" section in docs/guides/backend.md,
examples/server/api.md and the server README, the README of
scripts/diagnostica_termica, test/README.md and the fork history.

test: device_health_test covers the new rules and the C API (135
checks), device_health_option_test is new (30), termico_test covers
engines with two levels, one level and none declared (161), and
server_guardian_e2e.py starts its second server with
--device-health levels=2,step=20,quiet=5 and checks the option in sd-cli
(70 checks, three runs in a row with a synthetic SD 1.5 model). Every
program of test/ passes, the server tests under ThreadSanitizer too, and
29 broken versions of the new code (registry and C API 12, option 9,
termico.py 6, the calls in sd-server and sd-cli 2) all make the tests
fail. Not tried: real GPUs, Windows.

Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
Brings in the six upstream commits after 79dc7ca:
- idle weight release also clears the reusable buffers of the backends
  (leejet#2418);
- RelayVSR KV graph cuts, and DGL failures that say which memory ran out
  (leejet#2419);
- DGL jobs can be cancelled (leejet#2420);
- --api-key, --api-key-file and --cors-origins in server_access.{h,cpp}
  (leejet#2367);
- ClipProj-MiniMax-H3 without the MLP (leejet#2410);
- inline media previews in the DGL editor, GET /sdcpp/v1/view and
  --no-media-view (leejet#2423).

Conflicts, and how they were resolved:
- Server access. This fork had its own --api-key (one key) and
  --cors-origins (empty = reflect any origin) in a pre-routing handler in
  main.cpp. Upstream's SDHttpServer replaces them: the handler, its three
  helpers and the two string options are gone. What changes for clients:
  by default only the server's own origin is accepted, so a page of
  another origin gets 403, and so does a request whose Host is not
  localhost, the listen address or an IP; GET / and OPTIONS need no key;
  several keys and a key file are accepted. Programs that send no Origin
  (curl, Python, Node's fetch, termico.py) are not affected.
- Cancelling DGL jobs. Upstream stops a DGL job through the server's only
  context. Here a script runs on the keeper's context, or on a temporary
  one (ContextKeeper::with_context), so execute_dgl_job starts the
  JobCancellationMonitor inside with_context, with an action that calls
  sd_dgl_ctx_cancel on that context. The monitor takes its action as a
  callable, and the keeper-based monitor of the generation jobs is built
  on it. The fork's CancelToken (job.cancel.requested) stays in place of
  upstream's job.cancel_requested. The cancel route keeps ?wait= and now
  stops DGL jobs too.
- Console progress. Upstream turns console_progress on for the server's
  context; here the keeper's create_context hook turns it on for every
  context the keeper creates, after the file access policy.
- runtime.cpp: --disable-degradation and --no-media-view are both kept.
- include/stable-diffusion.h: the sd_dgl_ctx_set comment lists the fork's
  memory_guard and disable_backend_fallback and upstream's
  console_progress.
- api.md: the fork's description of the cancel route stays, and names DGL
  jobs.

Needed without a conflict: test/memory_guard_engine_test.cpp follows the
new ensure_compute_backend_capacity() signature.

test: test/server_cancel_e2e.py stops DGL jobs too: poll_url, progress,
a stop without ?wait=, a queued DGL job, ?wait=30, and a DGL job and an
image job that complete afterwards. The server it starts gets --model-dir
with the folder of the model, because a DGL script reads models only from
the model directories; --skip-dgl leaves the part out for models that are
not SD 1.x.

docs: docs/convivenza_applicazioni.md and docs/integrazione_progetti.md
describe the new default for origins and the 403; entry 25 of the fork
history describes this sync and what was tested; test/README.md lists
the new part of the cancel test.

Verified with a CPU build: the library, sd-cli and sd-server build
without warnings in the fork's files; all nine unit-test programs pass;
with the synthetic SD 1.5 model test/server_cancel_e2e.py passes its 46
checks (35 as before, 11 on DGL jobs), and against a server whose DGL
stop never reaches the script two of them fail; a scratch check of the
access control (31 checks: keys, key file, origins, a foreign Host,
GET /, preflight, /sdcpp/v1/view, bad options) and the scratch smoke test
of the server (22 checks) pass; Node's fetch, which an Electron main
process uses, still gets through; test/security_smoke.sh (19 checks),
termico_test.py (127) and agenti_guardiano_test.py (66, and 91 with a
real server once its jobs ask for 100 steps, as fix_to_claude already
does) pass; the DGL built-in catalog is current. Not tried: a real GPU,
Windows, a script that runs out of memory, a reverse proxy.

Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
Brings in the sync 5 merge of fork-pull (1d95e26): upstream's access
control (SDHttpServer with --api-key, --api-key-file and --cors-origins,
same origin by default), DGL jobs that report their progress and can be
stopped through the job routes, GET /sdcpp/v1/view and --no-media-view,
and the library fixes of leejet#2418, leejet#2419 and leejet#2410.

Conflicts:
- examples/server/main.cpp: the guardian's halted hook of the keeper
  stays next to the create_context hook, which now also turns
  console_progress on.
- examples/server/routes_dgl.cpp: POST /sdcpp/v1/dgl/jobs keeps the
  guardian's refusal inside upstream's with_dgl_errors, which replaces
  local_dgl_route; common/media_io.h goes, as upstream, and guardian.h
  stays.
- test/README.md: this branch's rows, with the DGL part of the
  server_cancel_e2e.py row from fork-pull.
- docs/integrazione_progetti.md merged without a conflict, but git put
  the sync 5 paragraph after entry 27; it is back at the end of entry 25,
  where fork-pull has it.

What changes on this branch: the guardian now also stops a DGL job that
is running when it halts the server, and the job ends failed with the
code halted; before, a DGL script could not be stopped and ran to its
end. examples/server/api.md and entry 26 of the fork history say so.

Verified with a CPU build of this tree: all twelve unit-test programs
pass; with the synthetic SD 1.5 model server_guardian_e2e.py passes its
70 checks, server_cancel_e2e.py its 46, agenti_guardiano_test.py 66
without a server and 91 with one; a scratch check of the guardian with a
DGL job (6 checks: the running script ends halted within 0.2 s with the
reason, a new script is refused with 503, the server resumes, a script
after the resume completes), the scratch access check (31) and the
scratch smoke test of the server (22) pass; security_smoke.sh (19
checks) and termico_test.py (161) pass; the DGL built-in catalog is
current. Not tried: a real GPU, Windows, ThreadSanitizer on the server
itself.

Claude-Session: https://claude.ai/code/session_01EhZzDBkuuMp1jBf4WtEySC
@filve filve closed this Nov 25, 2026
@coderabbitai

coderabbitai Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

Explain Change →

Caution

Review failed

The pull request is closed.

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants